package cn.gaily.eduucenter.controller;

import cn.gaily.commonutils.JwtUtils;
import cn.gaily.eduucenter.entity.UcenterMember;
import cn.gaily.eduucenter.service.UcenterMemberService;
import cn.gaily.eduucenter.util.ConstantWxUtils;
import cn.gaily.eduucenter.util.HttpClientUtils;
import cn.gaily.servicebase.exceptionhandler.GuliException;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Api(description = "微信支付接口")
@Controller
@RequestMapping("/api/ucenter/wx")
@CrossOrigin
public class WxApiController {

    @Autowired
    private UcenterMemberService ucenterMemberService;
    //第一步生成微信扫描二维码，直接请求微信提供的固定地址，携带一些参数访问生成二维码
    @GetMapping("/login")
    public String login(){
        String url = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        url = String.format(url,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu");

        return "redirect:" + url;
    }

    //第二步获取扫描人信息
    @GetMapping("/callback")
    public String callback(String code,String state){

        try {
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //拼接三个参数 ：id  秘钥 和 code值
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code
            );
            //请求拼接好的地址，得到返回两个值access_token和openid，使用httpclient
            String res = HttpClientUtils.get(accessTokenUrl);
            System.out.println("access_token信息和openid：" + res);
            //用gson解析下res,得到两个值
            Gson gson = new Gson();
            HashMap map = gson.fromJson(res, HashMap.class);
            String access_token = (String) map.get("access_token");
            String openid = (String) map.get("openid");

            UcenterMember ucenterMember = ucenterMemberService.getByOpenId(openid);
            if(ucenterMember == null){
                //再去请求最终地址
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                //拼接两个参数
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                String userInfo = HttpClientUtils.get(userInfoUrl);
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userInfoMap.get("nickname");
                String headimgurl = (String) userInfoMap.get("headimgurl");
                ucenterMember = new UcenterMember();
                ucenterMember.setNickname(nickname);
                ucenterMember.setAvatar(headimgurl);
                ucenterMemberService.save(ucenterMember);
            }
            String jwtToken = JwtUtils.getJwtToken(ucenterMember.getId(), ucenterMember.getNickname());
            return "redirect:http://localhost:3000?token="+jwtToken;
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new GuliException(20001,"登陆失败");
        }
    }

}
